import React, { useState, useEffect, useReducer } from 'react';
import { Tree, Table, Button } from 'antd';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';

function TreeTableDnD() {

    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
        },
    ];

    const [data, setData] = useState([
        {
            key: '1',
            name: 'Node1',
            status: 'open',
            children: [
                {
                    key: '11',
                    name: 'Node1.1',
                    status: 'open',
                },
                {
                    key: '12',
                    name: 'Node1.2',
                    status: 'open',
                },
            ],
        },
        {
            key: '2',
            name: 'Node2',
            status: 'open',
            children: [
                {
                    key: '21',
                    name: 'Node2.1',
                    status: 'open',
                },
                {
                    key: '22',
                    name: 'Node2.2',
                    status: 'open',
                },
            ],
        },
    ]);

    const onDragEnd = result => {
        const { source, destination } = result;
        if (!destination) {
            return;
        }
        const sourceList = [...data];
        const targetList = [...data];
        const obj = sourceList[source.index];
        sourceList.splice(source.index, 1);
        targetList.splice(destination.index, 0, obj);
        setData(targetList);
    };

    return (
        <DragDropContext onDragEnd={onDragEnd}>
            <Table columns={columns} dataSource={data} pagination={false} expandable={{ defaultExpandAllRows: true }}>
                {data.map((item, index) => (
                    <Droppable key={item.key} droppableId={item.key}>
                        {(provided, snapshot) => (
                            <Draggable key={item.key} draggableId={item.key} index={index}>
                                {(provided, snapshot) => (
                                    <tr
                                        ref={provided.innerRef}
                                        {...provided.draggableProps}
                                        >
                                        <td {...provided.dragHandleProps}><span style={{ cursor: 'move' }}>:::</span></td>
                                        <td>{item.name}</td>
                                        <td>{item.status}</td>
                                    </tr>
                                )}
                            </Draggable>
                        )}
                    </Droppable>
                ))}
            </Table>
        </DragDropContext>
    )
}

export default TreeTableDnD;